package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"
)

// Client 客户端结构
type Client struct {
	ServerIp   string
	ServerPort int
	Name       string
	conn       net.Conn
	exit       bool
}

// CreateClient 创建客户端
func CreateClient(serverIP string, serverPort int) *Client {
	client := &Client{
		ServerIp:   serverIP,
		ServerPort: serverPort,
	}

	// 连接服务器
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIP, serverPort))
	if err != nil {
		fmt.Println("conn fail , err = ", err)
		return nil
	}

	client.conn = conn

	return client
}

var serverIP string
var serverPort int

// 初始化
func init() {
	flag.StringVar(&serverIP, "ip", "localhost", "set server ip address(default is localhost)")
	flag.IntVar(&serverPort, "port", 10086, "set server port(default is 10086) ")
}

func main() {
	//命令行解析
	flag.Parse()
	client := CreateClient(serverIP, serverPort)
	if client == nil {
		fmt.Println(">>>>>>>>>>>>>>>>>connect server fail............")
	} else {
		fmt.Println(">>>>>>>>>>>>>>>>>connect server success............")
	}

	go client.receiveMsg()
	client.sendMsg()
}

// 接收消息 显示到标准输出
func (c *Client) receiveMsg() {
	_, err := io.Copy(os.Stdout, c.conn)
	if err != nil {
		fmt.Println("receiveMsg fail , err = ", err)
		return
	}
}

// 发送消息
func (c *Client) sendMsg() {
	for {
		var input string
		_, err := fmt.Scanln(&input)
		if err != nil {
			continue
		}
		_, err = c.conn.Write([]byte(input + "\n"))
		if err != nil {
			fmt.Println("sendMsg fail , err = ", err)
			return
		}
	}
}
